# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import base64
import datetime
import hashlib
from web_lib.page import Page
from web_lib.webutils import Response, expose, json, salvaInSessione, leggiInSessione, permalinkaTitle , change_schema
import Environment
from web_lib.session import Session as S
from lib.utils import *
from webEnv import *


@expose('/pg/ac_Operatore/<action>')
@expose('/pg/ac_Operatore/')
#@expose('/pg/ac_Faq')
def anagraficaOperatore(req, action=None):
    """
    """
    #from dao.Setconf import SetConf
    def __show__(req, action=None):
        from dao.Operatore import Operatore
        pageData = {'file': "/pg/ac_Operatore"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        from dao.Operatore import Operatore
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_username = req.form.get("fk_username")
        fk_email = req.form.get("fk_email")
        fk_id_role = req.form.get("fk_id_role")
        daos = Operatore().select(
                            batchSize=batchSize,
                            usern=fk_username,
                            email=fk_email,
                            idRole=fk_id_role,
                            offset=offset,
                            orderBy=sorting)
        count = Operatore().count(
                            usern=fk_username,
                            email=fk_email,
                            idRole=fk_id_role,
                            batchSize=None)

        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        from dao.Operatore import Operatore
        id = req.form.get("id")
        if id and id != "None":
            d = Operatore().getRecord(id=int(id))
        else:
            d = Operatore()
        pageData = {'file': "pg/addedit/ae_operatore",
                    "dao": d,
                    }
        return Page(req).render(pageData)



    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        from dao.Operatore import Operatore
        idrr = S(req).getUserId()
        id = req.form.get("id")
        if id != "None":
            d = Operatore().getRecord(id=int(id))
        else:
            d = Operatore()

        d.email = str(req.form.get("email"))
        d.cognome = str(req.form.get("cognome"))
        d.nome = str(req.form.get("nome"))
        d.genere = str(req.form.get("genere"))
        d.f_imei = str(req.form.get("f_imei"))
        d.f_idreg = str(req.form.get("f_idreg"))
        d.data_nascita = stringToDate(str(req.form.get("data_nascita")))
        d.mailing_list = bool(req.form.get("mailing_list"))
        d.privacy = bool(req.form.get("privacy"))
        d.tipo_operatore = str(req.form.get("tipo_operatore"))
        d.active = bool(req.form.get("active"))
        d.cellulare = str(req.form.get("cellulare"))
        d.last_modified = datetime.datetime.now()
        if id != "None":
            if str(req.form.get("username")) != d.username:
                d.username = str(req.form.get("username"))
                if len(str(req.form.get("password"))) > 3:
                    d.password = hashlib.md5(str(req.form.get("username")) + \
                                    str(req.form.get("password"))).hexdigest()
                    if not d.f_ean:
                        data = createbarcode(d.password[0:10])
                        if data:
                            d.f_ean = base64.b64encode(data)
                    if not d.f_qrcode:
                        stringa= "Cognome: " + str(d.cognome or "") + "\n" + \
                                    "Nome: " + str(d.nome or "") + "\n" + \
                                    "Email: " + str(d.email or "") + "\n"+ \
                                    "Cellulare: " + str(d.cellulare or "") + "\n" + \
                                    "Codice: " + str(d.password[0:10])
                        dataqrcode = createbarcodeqr(stringa)
                        if dataqrcode:
                            d.f_qrcode = base64.b64encode(dataqrcode)
                else:
                    url_red = "/pg/ac_Operatore/"
                    return Page(req).redirect(url_red)

        else:
            d.registration_date = datetime.datetime.now()
            d.username = str(req.form.get("username"))
            d.password = hashlib.md5(str(req.form.get("username")) + \
                            str(req.form.get("password"))).hexdigest()
            stringa= "Cognome: " + str(d.cognome or "") + "\n" + \
                    "Nome: " + str(d.nome or "") + "\n" + \
                    "Email: " + str(d.email or "") + "\n"+ \
                    "Cellulare: " + str(d.cellulare or "") + "\n" + \
                    "Codice: " + str(d.password[0:10])
            data = createbarcode(d.password[0:10])
            if data:
                d.f_ean = base64.b64encode(data)
            dataqrcode = createbarcodeqr(stringa)
            if dataqrcode:
                d.f_qrcode = base64.b64encode(dataqrcode)
        d.persist()
        url_red = "/pg/ac_Operatore/"
        return Page(req).redirect(url_red)



    def __delete__(req, action=None):
        """Cancella una riga"""
        from dao.Operatore import Operatore
        id = int(req.form.get("id"))
        d = Operatore().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __preview__(req, action=None):
        codice = req.args.get("codice")
        operKey = req.args.get("operKey")
        if codice and codice != "None" and codice != "":
            from dao.Ente import Ente
            ente = Ente().select(codice=codice)
            if ente:
                Environment.census = True
                Environment.sch = ente[0].denominazione_breve.lower().replace(" ", "")
                change_schema(req, ente[0].denominazione_breve.lower().replace(" ", ""))
        from dao.Operatore import Operatore
        get = True
        d = None
        if operKey and operKey != "" and operKey != "None":
            d = Operatore().select(passwordKey=operKey)
            if d:
                d = d[0]
        else:
            id = req.form.get("id")
            get = False
            d = Operatore().getRecord(id=id)
        if get:
            item = prep2json(d),
            jasoned = json.dumps(item,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
            #print "jasoned", jasoned
            Environment.census = False
            Environment.sch = None
            return Response(jasoned)
        else:
            pageData = {'file': "/pg/operatore",
                        "dao": d}
            return Page(req).render(pageData)

    if leggiInSessione(req, sezione="Main", chiave="schema") is None:
        url_red = "/pg/main"
    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    else:
        return __show__(req, action=action)
